const ReactSSR = require('react-dom/server')
const pug = require('pug')

module.exports = (serverBundle, template, ctx, next) => {
    if (ctx.request.method !== 'GET') return
    const context = {}
    if (!serverBundle) return console.log('Not finished loading serverBundle is not defined')
    const createApp = serverBundle.default
    const createStoreMap = serverBundle.createStoreMap
    const appStore = createStoreMap()
    const app = createApp(appStore, context, ctx.path)
    const appString = ReactSSR.renderToString(app)
    let result = {}
    if (context.url) {
        result.status = 302
        result.location = context.url
        ctx.status = result.status
        ctx.body = {
            Location: result.location
        }
        ctx.set({
            Location: result.location
        })
    } else {
        const initialState = appStore.getState()
        console.log('pug render')
        const templateText = pug.render(template, {
            appString,
            initialState: JSON.stringify(initialState),
            header: {
                title: 'ahm',
                keywords: '1,2,3,4',
                description: 'descriptiondescriptiondescriptiondescriptiondescriptiondescription',
                author: 'ahm',
                viewport: 'width=device-width, initial-scale=1.0',
                ...initialState.header
            }
        })
        console.log('templateText', templateText)
        // ctx.response.status = 200
        ctx.response.body = templateText
        // result.innerHtml = templateText
    }
    // return result
}
